package com.hymall.controller.admin;

import com.hymall.bean.MarketStorage;
import com.hymall.bean.common.BasePageInfo;
import com.hymall.bean.common.BaseRespVo;
import com.hymall.bean.common.CommonData;
import com.hymall.service.admin.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: 叶熠彬
 * @description: 对象存储
 * @date: 2022/7/18 11:43
 */
@RestController
@RequestMapping("admin/storage")
public class StorageController {
    @Autowired
    StorageService storageService;


    /**
     * 查询存储列表
     * 根据key（精确）和name（模糊）
     *
     * @author: 叶熠彬
     * @date: 2022/7/18 11:50
     * @param: [key, name, info]
     * @return: com.hymall.bean.common.BaseRespVo
     */
    @GetMapping("list")
    public BaseRespVo queryImageList(String key, String name, BasePageInfo info) {
        CommonData data = storageService.queryList(key, name, info);
        return BaseRespVo.ok(data);
    }

    /**
     * 上传图片
     *
     * @author: 叶熠彬
     * @date: 2022/7/18 15:19
     * @param: [file]
     * @return: com.hymall.bean.common.BaseRespVo
     */
    @PostMapping("create")
    public BaseRespVo createImage(MultipartFile file) {
        String contentType = file.getContentType();
        //上传的不是图片类型
        if (!"image".equals(contentType.split("/")[0])) {
            return BaseRespVo.invalidData();
        }
        MarketStorage storage = null;
        try {
            storage = storageService.addImage(file);
            return BaseRespVo.ok(storage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BaseRespVo.invalidData();
    }

    /**
     * 更新图片名称
     *
     * @author: 叶熠彬
     * @date: 2022/7/18 15:22
     * @param: [storage]
     * @return: com.hymall.bean.common.BaseRespVo
     */

    @PostMapping("update")
    public BaseRespVo updateImage(@RequestBody MarketStorage storage) {
        MarketStorage newStorage = storageService.updateImageName(storage);
        return BaseRespVo.ok(newStorage);
    }

    /**
     * 逻辑删除图片
     *
     * @author: 叶熠彬
     * @date: 2022/7/18 15:29
     * @param: [storage]
     * @return: com.hymall.bean.common.BaseRespVo
     */
    @PostMapping("delete")
    public BaseRespVo deleteImage(@RequestBody MarketStorage storage) {
        storageService.deleteImage(storage);
        return BaseRespVo.ok();
    }
}
